package com.cloud.phone.websocket;


import android.os.Handler;

import com.blankj.utilcode.util.LogUtils;
import com.cloud.phone.constants.Constants;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author : njb
 * @date : 2024/4/26 11:31
 * @desc : WSClient
 */

public class WSClient extends WebSocketClient {
    private static final String TAG = "MyWebSocketClient";
    private Handler mHandler;

    public WSClient(Handler handler, URI serverURI) {
        this(handler, serverURI, new Draft_6455());
    }

    public WSClient(Handler handler, URI serverUri, Draft draft) {
        this(handler, serverUri, new HashMap<String, String>(), draft, 1000);
    }

    public WSClient(Handler handler, URI serverUri, Map<String, String> headers, Draft draft, int connectTimeout) {
        super(serverUri, draft, headers, connectTimeout);
        this.mHandler = handler;
    }

    @Override
    public void onOpen(ServerHandshake handshakeData) {
        LogUtils.d(TAG, "onOpen: WebSocket连接打开了！");
        mHandler.sendEmptyMessage(Constants.WHAT_CONNECT_OPEN);
    }

    @Override
    public void onMessage(String message) {
        LogUtils.i(TAG, "onMessage: " + message);
        //处理信息
        mHandler.sendMessage(mHandler.obtainMessage(Constants.WHAT_HANDLE_RECEIVED_MSG, message));
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        LogUtils.i(TAG, "onClose: \ncode=" + code + "\nreason=" + reason + "\nremote=" + remote);
        wsClientListener.onCloseActive();
        if (remote) {
            LogUtils.i(TAG, "onClose: \ncode=" + code + "\nreason=" + reason + "\nremote=" + remote);
            mHandler.sendEmptyMessage(Constants.WHAT_REMOTE_INTERRUPT);
        } else {
            mHandler.sendEmptyMessage(Constants.WHAT_LOCAL_INTERRUPT);
        }
    }

    @Override
    public void onError(Exception exception) {
        LogUtils.i(TAG, "onError连接出错: " + exception.getMessage());
    }

    private WSClientListener wsClientListener;

    public void setWsClientListener(WSClientListener wsClientListener) {
        this.wsClientListener = wsClientListener;
    }

    interface WSClientListener {
        void onCloseActive();
    }

}
